#include <stdlib.h>

#include "etat_exploration.h"
#include "def_etat_exploration.h"
#include "parsing.h"

#include "constantes_et_macros.h"




void init_etat_exploration(struct etat_exploration* exploration,
                           const unsigned int id_region,
                           const struct base_donnees* donnees)
{
    int i;

    if(!(exploration->tab_zones = (struct zone**)malloc(81 * sizeof(struct zone*))))
        exit(EXIT_MALLOC);
    for(i = 0;  i < 81;  i++)
        exploration->tab_zones[i] = NULL;
    lire_fichier_pour_exploration(exploration, id_region, donnees);
}



void detruire_etat_exploration(struct etat_exploration* exploration)
{
    int i;

    for(i = 0;  i < 81;  i++)
        if(exploration->tab_zones[i])
            free(exploration->tab_zones[i]);
    free(exploration->tab_zones);
}



void marquer_zone_exploree(struct etat_exploration* exploration,
                           const unsigned int num_zone)
{
    int i;

    i = 0;
    while(!exploration->tab_zones[i] ||
          exploration->tab_zones[i]->id_zone != num_zone)
        i++;
    exploration->tab_zones[i]->exploree = VRAI;
}



struct zone* get_zone_exploration(const struct etat_exploration* exploration,
                                  const unsigned char x,
                                  const unsigned char y)
{
    return exploration->tab_zones[x + 9 * y];
}



char voir_si_zone_accessible(const struct etat_exploration* exploration,
                             const unsigned char x,
                             const unsigned char y)
{
    struct zone* p_zone;
    struct zone* p_voisine;

    p_zone = get_zone_exploration(exploration, x, y);
    /* on ne peut pas visiter deux fois la meme zone durant une exploration */
    if(p_zone->exploree)
        return FAUX;
    /*
     * la zone 1 est la zone d'arrivee, elle est donc
     * forcement accessible si pas encore exploree
     */
    if(p_zone->id_zone == 1)
        return VRAI;
    /*
     * il faut ensuite voir si une zone reliee a
     * celle qui nous interesse a ete exploree
     */
    if(p_zone->raccords[HAUT] && y > 0)
    {
        p_voisine = get_zone_exploration(exploration, x, y - 1);
        if(p_voisine && p_voisine->exploree)
            return VRAI;
    }
    if(p_zone->raccords[DROITE] && x < 8)
    {
        p_voisine = get_zone_exploration(exploration, x + 1, y);
        if(p_voisine && p_voisine->exploree)
            return VRAI;
    }
    if(p_zone->raccords[BAS] && y < 8)
    {
        p_voisine = get_zone_exploration(exploration, x, y + 1);
        if(p_voisine && p_voisine->exploree)
            return VRAI;
    }
    if(p_zone->raccords[GAUCHE] && x > 0)
    {
        p_voisine = get_zone_exploration(exploration, x - 1, y);
        if(p_voisine && p_voisine->exploree)
            return VRAI;
    }
    return FAUX;
}
